<script setup>
import { ref, onMounted } from 'vue'
import service from '@/utils/request'
import { ElMessage } from 'element-plus'

const deviceNumber = ref('AB9831171')
const historyData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const currentImage = ref(null)
const timeRange = ref('week') // 默认显示最近一周

// 时间范围选项
const timeRangeOptions = [
  { label: '最近一周', value: 'week' },
  { label: '最近半月', value: 'halfMonth' },
  { label: '最近一月', value: 'month' }
]

// 获取历史图片
const fetchHistoryImages = async () => {
  loading.value = true
  try {
    const { data } = await service.get(`/api/cameras/${deviceNumber.value}/images`)
    if (data && Array.isArray(data)) {
      // 根据时间范围过滤数据
      const now = new Date()
      const ranges = {
        week: 7,
        halfMonth: 15,
        month: 30
      }
      const daysAgo = ranges[timeRange.value]
      const filterDate = new Date(now.getTime() - daysAgo * 24 * 60 * 60 * 1000)

      historyData.value = data
        .filter(item => new Date(item.captureTime) > filterDate)
        .map(item => ({
          id: item.id,
          imageUrl: item.imageUrl,
          deviceName: item.device.name,
          deviceNumber: item.device.deviceNumber,
          date: new Date(item.captureTime).toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }),
          timestamp: new Date(item.captureTime)
        }))
        .sort((a, b) => b.timestamp - a.timestamp) // 按时间倒序排列
    }
  } catch (error) {
    console.error('获取历史图片失败:', error)
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

// 处理时间范围变化
const handleTimeRangeChange = () => {
  fetchHistoryImages()
}

// 预览图片
const handlePreview = (item) => {
  console.log('预览图片:', item) // 添加日志
  currentImage.value = item
  dialogVisible.value = true
}

// 下载图片
const handleDownload = (imageUrl) => {
  if (imageUrl) {
    window.open(imageUrl)
  }
}

onMounted(() => {
  fetchHistoryImages()
})

// 确保这个方法可以被外部调用
defineExpose({
  fetchHistoryImages
})
</script>

<template>
  <div class="panel video-history">
    <div class="panel-header">
      <span>历史监控记录</span>
      <div class="controls">
        <el-select 
          v-model="timeRange" 
          size="small"
          @change="handleTimeRangeChange"
        >
          <el-option 
            v-for="option in timeRangeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </div>
    </div>
    
    <div class="history-content">
      <el-timeline v-loading="loading">
        <template v-if="historyData.length === 0">
          <div class="no-data">暂无历史图片</div>
        </template>
        
        <el-timeline-item
          v-for="item in historyData"
          :key="item.id"
          :timestamp="item.date"
          type="primary"
          size="large"
          :hollow="true"
        >
          <div class="timeline-item">
            <div class="image-wrapper" @click="handlePreview(item)">
              <el-image 
                :src="item.imageUrl"
                fit="cover"
              >
                <template #error>
                  <div class="image-placeholder">
                    <el-icon><Picture /></el-icon>
                    <div>加载失败</div>
                  </div>
                </template>
                <template #placeholder>
                  <div class="image-placeholder">
                    <el-icon><Loading /></el-icon>
                    <div>加载中</div>
                  </div>
                </template>
              </el-image>
            </div>
            <div class="timeline-info">
              <div class="device-name">{{ item.deviceName }}</div>
              <div class="actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click="handlePreview(item)"
                >
                  <el-icon><ZoomIn /></el-icon>
                  预览
                </el-button>
                <el-button 
                  type="success" 
                  size="small"
                  @click="handleDownload(item.imageUrl)"
                >
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </div>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="图片详情"
      width="80%"
      :destroy-on-close="true"
      class="preview-dialog"
    >
      <div class="preview-content" v-if="currentImage">
        <div class="preview-image">
          <el-image
            :src="currentImage.imageUrl"
            fit="contain"
            :preview-src-list="[currentImage.imageUrl]"
          >
            <template #error>
              <div class="image-placeholder">图片加载失败</div>
            </template>
          </el-image>
        </div>
        <div class="preview-info">
          <div class="info-item">
            <span class="label">设备名称：</span>
            <span>{{ currentImage.deviceName }}</span>
          </div>
          <div class="info-item">
            <span class="label">抓拍时间：</span>
            <span>{{ currentImage.date }}</span>
          </div>
          <div class="info-item">
            <span class="label">设备编号：</span>
            <span>{{ currentImage.deviceNumber }}</span>
          </div>
          <el-button 
            type="primary"
            @click="handleDownload(currentImage.imageUrl)"
          >
            <el-icon><Download /></el-icon>
            下载图片
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.video-history {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.panel-header {
  flex-shrink: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.history-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 15px;
}

.image-item {
  background: rgba(0,47,167,0.2);
  border: 1px solid rgba(0,183,255,0.2);
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
}

.image-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,183,255,0.2);
}

.image-item .el-image {
  width: 100%;
  height: 120px;
  display: block;
}

.image-info {
  padding: 8px;
}

.time {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.device-name {
  font-size: 14px;
  color: #30f3f9;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.preview-content {
  display: flex;
  gap: 20px;
  height: 60vh;
}

.preview-image {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0,47,167,0.2);
  border-radius: 4px;
}

.preview-image .el-image {
  max-height: 100%;
  max-width: 100%;
}

.preview-info {
  flex: 1;
  padding: 20px;
  background: rgba(0,47,167,0.2);
  border-radius: 4px;
}

.info-item {
  margin-bottom: 15px;
  line-height: 1.5;
}

.label {
  color: #909399;
  margin-right: 10px;
}

:deep(.preview-dialog .el-dialog) {
  background: #001529;
  border: 1px solid rgba(0,183,255,0.2);
}

:deep(.preview-dialog .el-dialog__title) {
  color: #fff;
}

:deep(.preview-dialog .el-dialog__header) {
  border-bottom: 1px solid rgba(0,183,255,0.2);
}

.image-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(0,47,167,0.2);
  color: #909399;
  font-size: 14px;
  gap: 10px;
}

/* 自定义滚动条样式 */
.history-content::-webkit-scrollbar {
  width: 6px;
}

.history-content::-webkit-scrollbar-thumb {
  background: rgba(0,183,255,0.2);
  border-radius: 3px;
}

.history-content::-webkit-scrollbar-track {
  background: transparent;
}

.no-data {
  grid-column: 1 / -1;
  text-align: center;
  padding: 20px;
  color: #909399;
}

.timeline-item {
  display: flex;
  gap: 15px;
  background: rgba(0,47,167,0.1);
  padding: 10px;
  border-radius: 4px;
  border: 1px solid rgba(0,183,255,0.2);
}

.image-wrapper {
  width: 200px;
  height: 120px;
  overflow: hidden;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.image-wrapper:hover {
  transform: scale(1.02);
}

.timeline-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

:deep(.el-timeline-item__node--large) {
  background-color: var(--el-color-primary);
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
}

.actions {
  display: flex;
  gap: 10px;
}
</style> 